package com.grm.service.impl;

import com.grm.common.Result;
import com.grm.constant.UserConstant;
import com.grm.exception.BusinessException;
import com.grm.mapper.SysUserMapper;
import com.grm.model.SysUser;
import com.grm.request.LoginReq;
import com.grm.service.LoginService;
import com.grm.util.JwtUtil;
import com.grm.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public Result login(LoginReq loginReq) {
        SysUser sysUser = sysUserMapper.queryByUsername(loginReq.getUsername());
        if (sysUser == null) {
            throw new BusinessException("用户不存在！");
        }
        if (!sysUser.getPassword().equals(loginReq.getPassword())) {
            throw new BusinessException("密码错误！");
        }
        // 校验验证码
        String captchaCache = redisUtil.get(UserConstant.getCaptchaKey(loginReq.getUuid()));
        if (captchaCache == null) {
            throw new BusinessException("验证码已失效！");
        }
        if (!loginReq.getCaptcha().equals(captchaCache)) {
            throw new BusinessException("验证码错误！");
        }
        log.info("login success,username={}", loginReq.getUsername());
        String token = jwtUtil.createToken(loginReq.getUsername());
        // redis存token,2h有效期
        redisUtil.setExpire(UserConstant.getTokenKey(loginReq.getUsername()),token,2, TimeUnit.HOURS);
        return Result.success(token);
    }
}
